package com.zlh.rm.DAO.Impl;

import java.util.Iterator;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.mapping.Collection;
import com.zlh.rm.DAO.IBaseDao;
import com.zlh.rm.Exception.Dao.SystemCode;
import com.zlh.rm.Exception.Dao.SystemException;

/** 
 * @author zuolh 
 * 
 */  
public class BaseDao implements IBaseDao {  
    private SessionFactory sessionFactory;
    private Logger logger = LogManager.getLogger(this.getClass());

    // private Messages Messages=new Messages();  
  
//    private String databeaseError = Messages
//            .getString("BaseDao.databeaseError");
  
//    private SessionFactory sessionFactory;  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#batchDelete(java.lang.Class, long[]) 
     */  
    public void batchDelete(Class clazz, long[] id) {  
        // TODO Auto-generated method stub  
          
        String strId = "";  
          
        for (int i = 0; i < id.length; i++) {  
              
            if (i > 0)  
                  
                strId += ", " + id[i];  
              
            else  
                  
                strId = "" + id[i];  
              
        }  
        logger.debug("batchDelete(Class, long[])  id[]={" + strId + "}");  
          
        for (int i = 0; i < id.length; i++) {  
              
            this.delete(clazz, id[i]);  
              
        }  
  
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#create(java.lang.Object) 
     */  
    public void create(Object entity) {  
        // TODO Auto-generated method stub  
          
        Session session = null;  
          
        Transaction tr = null;  
          
        boolean commitflag=false;  
          
        try {  
            session = this.getSession();  
              
            tr = session.beginTransaction();   
              
            session.save(entity);  
              
            tr.commit();  
              
            commitflag=true;  
              
            session.flush();  
              
            session.clear();  
              
            // super.getHibernateTemplate().save(entity);  
              
            logger.debug("保存" + entity.getClass().getName() + " 的实例到数据库成功！");  
  
        } catch (Exception e) {   
              
                  
//            String error = Messages.getString("BaseDao.create.saveError");  
              
            logger.debug("保存" + entity.getClass().getName() + " 的实例到数据库 ,"  
                        + SystemCode.SAVE_ERROR, e);

            e.printStackTrace();  
              
            throw new SystemException(SystemCode.SAVE_ERROR);  
              
        } finally {  
              
            if(!commitflag)  
            {  
                try{  
                      
                    if (tr != null)  
                          
                        tr.rollback();  
                      
                }catch(Exception e1)  
                {  
                          
                    logger.debug("事务",e1);  
                      
                }  
            }  
              
            this.closeSession(session);  
  
        }  
  
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#delete(java.lang.Object) 
     */  
    public void delete(Object entity) {  
        // TODO Auto-generated method stub  
          
        logger.debug("delete(Object) entity.class="  
                + entity.getClass().getName());   
          
        Session session = null;  
          
        Transaction tr = null;  
          
        boolean commitflag=false;  
          
        try {  
  
            session = this.getSession();  
              
            tr = session.getTransaction();  
              
            tr.begin();  
              
            session.delete(entity);  
              
            tr.commit();  
              
            commitflag=true;  
              
            session.flush();  
              
            session.clear();  
  
        } catch (Exception e) {  
              
            if (tr != null)  
                  
                tr.rollback();  
              
//            String Error = Messages.getString("BaseDao.delete.Error");  
  
            logger.debug(e.getMessage() + " Class=" + entity.getClass().getName(), e);  
              
//            throw new SystemException(SystemCode.DELETE_ERROR); 
            throw new SystemException(SystemCode.DELETE_ERROR);
        } finally {  
              
            if(!commitflag)  
            {  
                try  
                {  
                    if (tr != null)  
                          
                        tr.rollback();  
                      
                }catch(Exception e)  
                {  
                    e.printStackTrace();  
                }  
            }  
              
            this.closeSession(session);  
              
        }  
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#delete(java.lang.Class, long) 
     */  
    public void delete(Class clazz, long id) {  
        // TODO Auto-generated method stub  
          
        logger.debug("ClassName=" + clazz.getName() + "  ,id=" + id);  
          
        try {  
  
            Object entity = this.getByPk(clazz, id);  
              
            if (entity != null)  
                  
                this.delete(entity);  
              
            else  
                  
                logger.debug(clazz.getName() + " 的关键字为 " + id + "  的对象不存在 ");  
  
        } catch (Exception e) {  
              
            logger.debug("  delete(Class, long)  excute is error  . Error="  
                    + e.toString());  
              
//            throw new SystemException(Messages.getString("BaseDao.delete.Error"));
            throw new SystemException(SystemCode.DELETE_ERROR);
  
        }  
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#deleteAll(java.lang.Class) 
     */  
    public void deleteAll(Class clazz) {  
        // TODO Auto-generated method stub  
          
        logger.debug("deleteAll(Class) ClassName=" + clazz.getName());   
          
        Session session = null;  
          
        Transaction tr = null;  
          
        boolean commitflag=false;  
  
        try {  
                          
            session = this.getSession();  
              
            tr = session.beginTransaction();  
              
            Query query = session.createQuery(" delete   from "  
                    + clazz.getName());  
              
            query.executeUpdate();  
              
            tr.commit();  
              
            commitflag=true;  
              
            session.flush();  
              
        } catch (Exception e) {   
              
//            String Error = Messages.getString("BaseDao.delete.Error");  
              
            logger.debug("从数据库中删除" + clazz.getName() + "的所实例失败！", e);  
              
            throw new SystemException(SystemCode.DELETE_ERROR);  
              
        } finally {  
              
            if(!commitflag)  
            {  
                try  
                {  
                    if (tr != null)  
                          
                        tr.rollback();  
                      
                }catch(Exception e)  
                {  
                    e.printStackTrace();  
                }  
            }  
              
            this.closeSession(session);  
              
        }  
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#deleteAll(java.util.Collection) 
     */  
    public void deleteAll(Collection entities) {  
        // TODO Auto-generated method stub  
          
        Session session = null;  
          
        Transaction tr = null;  
          
        boolean commitflag=false;  
          
        try {  
              
            session = this.getSession();  
              
            tr = session.beginTransaction();  
              
            Iterator ite = entities.getColumnIterator();  
              
  
            while (ite.hasNext())  
                  
                session.delete(ite.next());  
              
            // super.getHibernateTemplate().deleteAll(entities);  
            tr.commit();  
              
            commitflag=true;  
              
            session.flush();  
              
  
        } catch (Exception e) {   
              
//            String error = Messages.getString("BaseDao.deleteAll.Error");  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DELETE_ALL_ERROR);  
              
        } finally {  
              
            if(!commitflag)  
            {  
                try  
                {  
                    if (tr != null)  
                          
                        tr.rollback();  
                      
                }catch(Exception e)  
                {  
                    e.printStackTrace();  
                }  
            }  
              
            this.closeSession(session);  
              
        }  
          
          
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#excuteSql(java.lang.String) 
     */  
    public void excuteSql(String strsql) {  
        // TODO Auto-generated method stub  
          
        logger.debug("excuteSql(String) strsql=" + strsql);  
          
        Session session = null;  
          
        Transaction tr = null;  
          
        boolean commitflag=false;  
          
        try {  
              
            session = this.getSession();  
              
            tr = session.beginTransaction();  
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
              
            query.executeUpdate();  
              
            tr.commit();  
              
            commitflag=true;  
              
            session.flush();  
              
            // super.getHibernateTemplate().update(entity);  
  
        } catch (Exception e) {  
              
               
              
//            String Error = Messages.getString("BaseDao.excuteSql.Error");  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.EXECUTE_SQL_ERROR);
              
        } finally {  
              
            if(!commitflag)  
            {  
                try  
                {  
                    if (tr != null)  
                          
                        tr.rollback();  
                      
                }catch(Exception e)  
                {  
                    e.printStackTrace();  
                }  
            }  
              
            this.closeSession(session);  
              
        }  
   
          
  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#find(java.lang.String) 
     */  
    public List find(String strhql) {  
        // TODO Auto-generated method stub  
          
        List result = null;  
          
        logger.debug("find(String) queryString=" + strhql);  
          
        Session session = null;  
          
        try {  
              
            // result = super.getHibernateTemplate().find(queryString);  
              
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
              
            result = query.list();  
  
        } catch (Exception e) {  
              
            logger.debug("执行数据库中查询时失败,语句为：" + strhql, e);  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;   
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#find(java.lang.String, java.lang.Object) 
     */  
    public List find(String strhql, Object param) {  
        // TODO Auto-generated method stub  
          
        logger.debug("find(String, Object) queryString=" + strhql  
                + " ,param=" + param);  
  
        List result = null;  
          
        Session session = null;  
          
        try {  
  
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
              
            query.setParameter(0, param);  
              
            result = query.list();  
  
            // result = super.getHibernateTemplate().find(queryString, param);  
  
        } catch (Exception e) {  
              
            logger.debug(SystemCode.DATABASE_ERROR, e);  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
  
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
           
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#findByNamedParam(java.lang.String, java.lang.String, java.lang.Object) 
     */  
    public List findByNamedParam(String strhql, String name, Object param) {  
        // TODO Auto-generated method stub  
  
  
        logger.debug("findByNamedParam(String, String, Object) strhql="  
                + strhql + "name=" + name + " ,param=" + param);  
  
        List result = null;  
          
        Session session = null;  
          
        try {  
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
              
            query.setParameter(name, param);  
              
            result = query.list();  
  
            // result =  
            // super.getHibernateTemplate().findByNamedParam(queryString,  
            // name, param);  
  
        } catch (Exception e) {  
              
            logger.debug(SystemCode.DATABASE_ERROR, e);  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
  
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#findBySql(java.lang.String) 
     */  
    public List findBySql(String strsql) {  
        // TODO Auto-generated method stub  
          
        logger.debug("exceuteSQL(String) strsql=" + strsql);  
          
        System.out.println(strsql);  
          
        Session session = null;  
          
        List result=null;  
          
          
        try {  
              
            session = this.getSession();   
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
            result=query.list();  
              
            // super.getHibernateTemplate().update(entity);  
  
        } catch (Exception e) {   
              
//            String Error = Messages.getString("BaseDao.exceuteSQL.Error");  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.EXECUTE_SQL_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#findBySql(java.lang.String, java.util.List) 
     */  
    public List findBySql(String strsql, List params) {  
        // TODO Auto-generated method stub  
  
        String paramnameArray="";   
           
        if(params!=null)  
        {  
              
            for (int i = 0; i < params.size(); i++) {  
                      
                    if (i > 0)  
                          
                        paramnameArray += " , " + params.get(i);  
                      
                    else  
                          
                        paramnameArray = ""+params.get(i);  
                      
            }  
          
        }  
          
        logger.debug("excuteSql(String, List) strsql="+strsql+" , List="+paramnameArray);  
          
        System.out.println(strsql);  
          
        List result =null;  
          
        Session session = null;  
          
        try {   
              
            session = this.getSession();  
              
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
            if(params!=null)  
            {  
                for (int i = 0; i < params.size(); i++) {  
                                          
                    query.setParameter(i, params.get(i));  
                      
                }   
            }  
              
            result  = query.list();  
  
        } catch (Exception e) {  
              
//            String error = Messages.getString("BaseDao.findBySql.Error");  
              
            logger.debug(e.getMessage());  
              
            e.printStackTrace();  
              
            throw new SystemException(SystemCode.FINDE_BY_SQL_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;    
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getByPk(java.lang.Class, int) 
     */  
    public Object getByPk(Class clazz, int id) {  
        // TODO Auto-generated method stub  
  
  
        logger.debug("getByPk(Class, Integer) class=" + clazz.getName()  
                + " , ID=" + id);  
          
        Object result = null;  
          
        Session session = null;  
          
        try {  
              
            session = this.getSession();  
              
            result = session.get(clazz, new Integer(id));             
  
        } catch (Exception e) {
            logger.debug(SystemCode.DATABASE_ERROR, e);  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
  
        return result;  
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getByPk(java.lang.Class, long) 
     */  
    public Object getByPk(Class clazz, long id) {  
        // TODO Auto-generated method stub  
  
        logger.debug("getByPk(Class, Long) Class=" + clazz.getName() + ",id="  
                + id);  
          
        Object result = null;  
          
        Session session = null;  
          
        try {  
            session = this.getSession();  
              
            result = session.get(clazz, new Long(id));  
              
            // (Object) super.getHibernateTemplate().get(clazz, id);  
  
        } catch (Exception e) {  
              
            logger.debug(SystemCode.DATABASE_ERROR, e);  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
  
        return result;  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getByPk(java.lang.Class, java.lang.String) 
     */  
    public Object getByPk(Class clazz, String id) {  
        // TODO Auto-generated method stub  
  
        logger.debug("getByPk(Class, String) Class=" + clazz.getName() + ",id="  
                + id);  
          
        Object result = null;  
          
        Session session = null;  
          
        try {  
  
            session = this.getSession();  
              
            result = session.get(clazz, id);  
              
            // result = (Object) super.getHibernateTemplate().get(clazz, id);  
  
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
  
        return result;  
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getSession() 
     */  
    public Session getSession() {  
        // TODO Auto-generated method stub  
        return sessionFactory.openSession();
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getTotalCount(java.lang.String) 
     */  
    public int getTotalCount(String strhql) {  
        // TODO Auto-generated method stub  
  
        logger.debug("getTotalCount() strhql=" + strhql);  
          
        int result = 0;  
          
        Session session = null;  
          
        try {  
              
            String strsql = this.getQueryTotalCountString(strhql);  
              
            session = this.getSession();  
              
            Query query = session.createQuery(strsql);  
              
            List list = query.list();  
              
            result = this.getNum(list);  
              
        } catch (Exception e) {  
  
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getTotalCount(java.lang.String, java.lang.Object) 
     */  
    public int getTotalCount(String strhql, Object obj) {  
        // TODO Auto-generated method stub  
          
        logger.debug("getTotalCount(String,Object)  strhql=" + strhql  
                + "" + obj.getClass().getName());  
  
        int result = 0;  
          
        Session session = null;  
          
        try {  
              
            String strsql = this.getQueryTotalCountString(strhql);  
              
            //System.out.println(strsql);  
              
            logger.debug("strsql="+strsql);  
              
            session = this.getSession();  
              
            Query query = session.createQuery(strsql);  
              
            List list = query.setProperties(obj).list();   
                  
            result = this.getNum(list);  
              
  
        } catch (Exception e) {  
              
//            String error = Messages.getString("BaseDao.getTotalCount.Error");  
              
            logger.debug(e.getMessage());  
              
            e.printStackTrace();  
              
            throw new SystemException(SystemCode.GET_TOTAL_COUNT_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getTotalCount(java.lang.String, java.util.List) 
     */  
    public int getTotalCount(String strhql, List params) {  
        // TODO Auto-generated method stub  
          
        String paramnameArray="";   
           
        if(params!=null)  
        {  
              
            for (int i = 0; i < params.size(); i++) {  
                      
                    if (i > 0)  
                          
                        paramnameArray += " , " + params.get(i);  
                      
                    else  
                          
                        paramnameArray = ""+params.get(i);  
                      
            }  
          
        }  
          
        logger.debug("getTotalCount(String, List) strhql="+strhql+" , List="+paramnameArray);  
          
          
        int result = 0;  
          
        Session session = null;  
          
        try {  
              
            String strquery = this.getQueryTotalCountString(strhql);  
              
            //System.out.println(strsql);  
              
            session = this.getSession();  
              
            logger.debug("strquery=="+strquery);  
              
            Query query = session.createQuery(strquery);  
              
            if(params!=null)  
            {  
                for (int i = 0; i < params.size(); i++) {  
                                          
                    query.setParameter(i, params.get(i));  
                      
                }   
            }  
              
            List list = query.list();  
  
            result = this.getNum(list);  
              
  
        } catch (Exception e) {  
              
//            String error = Messages.getString("BaseDao.getTotalCount.Error");  
              
            logger.debug(e.getMessage());  
              
            e.printStackTrace();  
              
            throw new SystemException(SystemCode.GET_TOTAL_COUNT_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;    
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getTotalCountBySql(java.lang.String) 
     */  
    public int getTotalCountBySql(String strsql) {  
        // TODO Auto-generated method stub  
          
        logger.debug("getTotalCountBySql(String) strsql=" + strsql);  
          
        int result = 0;  
          
        Session session = null;  
          
        try {  
              
            strsql = this.getQueryTotalCountString(strsql);  
              
            session = this.getSession();   
              
            logger.debug("strsql=="+strsql);  
              
            List list=session.createSQLQuery(strsql).list();  
               
            result = this.getNum(list);  
              
        } catch (Exception e) {  
  
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
           
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#getTotalCountBySql(java.lang.String, java.util.List) 
     */  
    public int getTotalCountBySql(String strsql, List params) {  
        // TODO Auto-generated method stub  
          
        String paramnameArray="";   
           
        if(params!=null)  
        {  
              
            for (int i = 0; i < params.size(); i++) {  
                      
                    if (i > 0)  
                          
                        paramnameArray += " , " + params.get(i);  
                      
                    else  
                          
                        paramnameArray = ""+params.get(i);  
                      
            }  
          
        }  
          
        logger.debug("getTotalCountBySql(String, List) strsql="+strsql+" , List="+paramnameArray);  
          
          
        int result = 0;  
          
        Session session = null;  
          
        try {  
              
            strsql = this.getQueryTotalCountString(strsql);  
              
            logger.debug("strsql=="+strsql);  
              
            session = this.getSession();  
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
            if(params!=null)  
            {  
                for (int i = 0; i < params.size(); i++) {  
                                          
                    query.setParameter(i, params.get(i));  
                      
                }   
            }  
              
            List list = query.list();  
  
            result = this.getNum(list);  
              
  
        } catch (Exception e) {  
              
//            String error = Messages.getString("BaseDao.getTotalCount.Error");  
              
            logger.debug(e.getMessage());  
              
            e.printStackTrace();  
              
            throw new SystemException(SystemCode.GET_TOTAL_COUNT_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
           
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#loadAll(java.lang.String) 
     */  
    public List loadAll(String strhql) {  
        // TODO Auto-generated method stub  
        return this.find(strhql);  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#loadByPk(java.lang.Class, java.lang.String, java.lang.Object) 
     */  
    public Object loadByPk(Class clazz, String keyName, Object keyValue) {  
        // TODO Auto-generated method stub  
          
        Object result = null;  
          
        String query = "from " + clazz.getName() + "  where " + keyName + "=? ";  
          
        logger.debug("loadByPk(Class, String, Object) queryString=" + query  
                + "  ,keyValue=" + keyValue);  
          
        Session session = null;  
          
        try {  
  
            session = this.getSession();  
          
            result = session.createCriteria(clazz).add(  
                    Restrictions.eq(keyName, keyValue)).list();  
              
  
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;        
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#query(int, int, java.lang.String) 
     */  
    public List query(int pageNo, int pageSize, String strhql) {  
        // TODO Auto-generated method stub  
  
        logger.debug("query(int, int, String) pageNo=" + pageNo + ",pageSize="  
                + pageSize + " ,strhql=" + strhql);  
  
        List result = null;  
          
        Session session = null;  
          
        try {  
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
            //System.out.println(queryString);  
              
            if (pageNo > 0 && pageSize > 0) {  
                  
                query.setFirstResult((pageNo - 1) * pageSize);  
                  
                query.setMaxResults(pageSize);  
            }  
              
            result = query.list();  
              
            //System.out.println()  
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#query(int, int, java.lang.String, java.lang.Object) 
     */  
    public List query(int pageNo, int pageSize, String strhql, Object obj) {  
        // TODO Auto-generated method stub  
  
        logger.debug("query(int, int, String, Object) pageNo=" + pageNo  
                + ",pageSize=" + pageSize + "strhql="+strhql+"  ,obj"  
                + obj.getClass().getName());  
          
        List result = null;  
          
        Session session = null;  
          
        try {  
              
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
              
            query.setProperties(obj);  
              
            if (pageNo > 0 && pageSize > 0) {  
                  
                query.setFirstResult((pageNo - 1) * pageSize);  
                  
                query.setMaxResults(pageSize);  
                  
            }  
              
            result = query.list();  
              
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;  
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#query(int, int, java.lang.String, java.util.List) 
     */  
    public List query(int pageNo, int pageSize, String strhql, List params) {  
        // TODO Auto-generated method stub  
  
        logger.debug("query(int, int, String, Object) pageNo=" + pageNo + ",pageSize=" + pageSize + ",strhql="+strhql);       
          
        String paramnameArray="";  
          
        if(params!=null)  
        {  
              
            for (int i = 0; i < params.size(); i++) {  
                      
                    if (i > 0)  
                          
                        paramnameArray += " , " + params.get(i);  
                      
                    else  
                          
                        paramnameArray = ""+params.get(i);  
                      
            }  
          
        }  
          
        logger.debug("params="+params);  
          
        List result = null;  
          
        Session session = null;  
          
        try {  
              
            session = this.getSession();  
              
            Query query = session.createQuery(strhql);  
              
            if(params!=null)  
            {  
                for (int i = 0; i < params.size(); i++) {  
                                          
                    query.setParameter(i, params.get(i));  
                      
                }   
            }  
              
            if (pageNo > 0 && pageSize > 0) {  
                  
                query.setFirstResult((pageNo - 1) * pageSize);  
                  
                query.setMaxResults(pageSize);  
                  
            }  
              
            result = query.list();  
              
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;   
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#queryBySql(int, int, java.lang.String) 
     */  
    public List queryBySql(int pageNo, int pageSize, String strsql) {  
        // TODO Auto-generated method stub  
  
  
        logger.debug("query(int, int, String) pageNo=" + pageNo + ",pageSize="  
                + pageSize + " ,strsql=" + strsql);  
  
        List result = null;  
          
        Session session = null;  
          
        try {  
              
            session = this.getSession();              
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
            if (pageNo > 0 && pageSize > 0) {  
                  
                query.setFirstResult((pageNo - 1) * pageSize);  
                  
                query.setMaxResults(pageSize);  
                  
            }  
              
            result = query.list();  
              
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
          
        return result;   
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#queryBySql(int, int, java.lang.String, java.util.List) 
     */  
    public List queryBySql(int pageNo, int pageSize, String strsql, List params) {  
        // TODO Auto-generated method stub  
  
        logger.debug("query(int, int, String, Object) pageNo=" + pageNo + ",pageSize=" + pageSize + " , strsql="+strsql);         
          
        String paramnameArray="";  
          
        if(params!=null)  
        {  
              
            for (int i = 0; i < params.size(); i++) {  
                      
                    if (i > 0)  
                          
                        paramnameArray += " , " + params.get(i);  
                      
                    else  
                          
                        paramnameArray = ""+params.get(i);  
                      
            }  
          
        }  
          
        logger.debug("params="+params);  
          
        List result = null;  
          
        Session session = null;  
          
        try {  
              
            session = this.getSession();  
              
            SQLQuery query = session.createSQLQuery(strsql);  
              
            if(params!=null)  
            {  
                for (int i = 0; i < params.size(); i++) {  
                                          
                    query.setParameter(i, params.get(i));  
                      
                }   
            }  
              
            if (pageNo > 0 && pageSize > 0) {  
                  
                query.setFirstResult((pageNo - 1) * pageSize);  
                  
                query.setMaxResults(pageSize);  
                  
            }  
              
            result = query.list();  
              
        } catch (Exception e) {  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.DATABASE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
        return result;   
          
    }  
  
    /* (non-Javadoc) 
     * @see com.zlh.rm.DAO.IBaseDao#update(java.lang.Object) 
     */  
    public void update(Object entity) {  
        // TODO Auto-generated method stub  
          
        logger.debug("update(Object) entity.class="  
                + entity.getClass().getName());  
          
        Session session = null;  
          
        Transaction tr = null;  
          
        try {  
            session = this.getSession();  
              
            tr = session.beginTransaction();  
              
            session.update(entity);  
              
            tr.commit();  
              
            session.flush();  
              
            session.clear();  
              
            // super.getHibernateTemplate().update(entity);  
  
        } catch (Exception e) {  
              
            if (tr != null)  
                  
                tr.rollback();  
              
//            String Error = Messages.getString("BaseDao.update.Error");  
              
            logger.debug(e.getMessage());  
              
            throw new SystemException(SystemCode.UPDATE_ERROR);  
              
        } finally {  
              
            this.closeSession(session);  
              
        }  
  
    }  
      
    /** 
     * 功能：关闭session 
     * @param session 
     */  
    protected void closeSession(Session session) {  
  
        if (session != null && session.isOpen())  
              
            session.close();  
          
        session = null;  
          
    }  
      
    /** 
     * 功能：得到查询记录总数的语句（包含sql与hql 
     * @param queryString 
     * @return 
     */  
    private String getQueryTotalCountString(String queryString) {  
  
        int form_index = queryString.indexOf("from ");  
          
        int orderby_index = queryString.indexOf(" order by ");  
          
        if (form_index < 0) {  
              
//            throw new SystemException(Messages  
//                    .getString("BaseDao.getTotalCount.notFromkeyword"));  
          throw new SystemException(SystemCode.GET_TOTAL_COUNT_NOT_FROM_KEYWORD);
        }  
          
        String strsql = " select count(*) ";  
          
        if (orderby_index > -1) {  
              
            strsql = strsql + queryString.substring(form_index, orderby_index);  
  
        } else {  
              
            strsql = strsql + queryString.substring(form_index);  
        }  
  
        return strsql;  
    }  
      
    /** 
     * 功能：得到记录数的方法 
     * @param list 
     * @return 
     */  
    protected int getNum(List list)  
    {  
          
        int result=0;  
          
        if (list != null || list.size() > 0)   
              
            result = Integer.parseInt(list.get(0).toString());  
          
         return result;  
    }
} 
